package com.yehui.alibaba.service.tcc.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.yehui.alibaba.dao.AccountDAO;
import com.yehui.alibaba.service.tcc.TCCAccountService;
import io.seata.core.context.RootContext;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author 业徽
 * @date 2021/8/5
 */
@Service
public class TCCAccountServiceImpl implements TCCAccountService {

    private static final Logger logger = LoggerFactory.getLogger(TCCAccountServiceImpl.class);

    @Resource
    private AccountDAO accountDao;

    /**
     * 扣除余额
     *
     * @param userId 用户编号
     * @param price  扣减金额
     * @throws Exception 失败时抛出异常
     */
    @Override
    @DS(value = "account-ds")
    @Transactional(propagation = Propagation.REQUIRES_NEW) // 开启新事物
    public void reduceBalance(BusinessActionContext actionContext, Long userId, Integer price) throws Exception {
        logger.info("[reduceBalance] 当前 XID: {}", RootContext.getXID());

        // 检查余额
        checkBalance(userId, price);

        logger.info("[reduceBalance] 开始扣减用户 {} 余额", userId);
        // 扣除余额
        int updateCount = accountDao.reduceBalance(price);
        // 扣除成功
        if (updateCount == 0) {
            logger.warn("[reduceBalance] 扣除用户 {} 余额失败", userId);
            throw new Exception("余额不足");
        }
        logger.info("[reduceBalance] 扣除用户 {} 余额成功", userId);
    }

    /**
     * Commit boolean.
     *
     * @param actionContext the action context
     * @return the boolean
     */
    @Override
    public boolean tccCommit(BusinessActionContext actionContext) {
        logger.info("tcc 提交. txId={}, context={}", RootContext.getXID(), actionContext);
        return true;
    }

    /**
     * Rollback boolean.
     *
     * @param actionContext the action context
     * @return the boolean
     */
    @Override
    public boolean tccRollback(BusinessActionContext actionContext) {
        logger.info("tcc 回滚. txId={}, context={}", RootContext.getXID(), actionContext);
        return true;
    }

    private void checkBalance(Long userId, Integer price) throws Exception {
        logger.info("[checkBalance] 检查用户 {} 余额", userId);
        Integer balance = accountDao.getBalance(userId);
        if (balance < price) {
            logger.warn("[checkBalance] 用户 {} 余额不足，当前余额:{}", userId, balance);
            throw new Exception("余额不足");
        }
    }
}
